package ewa

import (
	"fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "time"
)

type MysqlConnArgs struct {
	Username string
	Password string
	Server string
	Port int
	Database string
}

func CreateMysqlConn(conn MysqlConnArgs) *sql.DB {
	var err error
	var db *sql.DB
	dsn := fmt.Sprintf( "%s:%s@%s(%s:%d)/%s", conn.Username, conn.Password, "tcp", conn.Server, conn.Port, conn.Database )
    db,err = sql.Open("mysql",dsn)
    if err != nil{
        r:=fmt.Sprintf("---MySQL/> Open mysql failed, err:%v\n", err); Log(r)
        return nil
    } else {
	    db.SetConnMaxLifetime(100 * time.Second)  //最大连接周期，超过100秒 的连接就close
	    db.SetMaxOpenConns(100) //设置最大连接数
	    db.SetMaxIdleConns(16) //设置闲置连接数
	    if Logoption.Mysqlquery == "true" {
	    	l:=fmt.Sprintf("---MySQL/> %s@%s(%s:%d)/%s Connected", conn.Username, "tcp", conn.Server, conn.Port, conn.Database); Log(l)
	    }
	    return db
   	}
}

func CloseMysqlConn(db *sql.DB) {
	db.Close()
}
